package com.central.file.config;

import cn.hutool.core.util.StrUtil;
import com.central.file.model.FileInfo;
import com.central.file.properties.FileServerProperties;
import com.central.file.service.impl.AbstractIFileService;
import com.central.file.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

@Configuration
@ConditionalOnProperty(name = "zlt.file-server.type", havingValue = "local")
public class LocalFileConfig {

    @Autowired
    private FileServerProperties fileProperties;

    @Value("${zlt.file-server.rootPath}")
    private String rootPath;

    @Service
    public class LocalFileServerImpl extends AbstractIFileService {
        @Override
        protected String fileType() {
            return fileProperties.getType();
        }

        @Override
        protected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {
            String path = rootPath +"\\"+ fileType() +"\\" + fileInfo.getName();
            FileUtil.saveFile(file, path);
            fileInfo.setPath(path);
            fileInfo.setUrl(path);
        }

        @Override
        protected boolean deleteFile(FileInfo fileInfo) {
            if (fileInfo != null && StrUtil.isNotEmpty(fileInfo.getPath())) {
                FileUtil.deleteFile(fileInfo.getPath());
            }
            return true;
        }

        @Override
        public void downLoad(String id, HttpServletResponse response) throws Exception {
            FileInfo fileInfo = super.getById(id);
            File file = new File(fileInfo.getPath());
            FileInputStream inputStream = new FileInputStream(file);
            response.setContentType(fileInfo.getContentType());
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0L);
            ServletOutputStream outputStream = response.getOutputStream();
            int n = 0;// 每次读取的字节长度
            byte[] bb = new byte[1024];// 存储每次读取的内容
            while ((n = inputStream.read(bb)) != -1) {
                outputStream.write(bb, 0, n);// 将读取的内容，写入到输出流当中
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        }
    }


}
